﻿using MediatR;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.RBAC;
using RBAC.Api.Read.Dto;

namespace RBAC.Api.Read.CommandHandler.RBAC
{
    public class GetMenuPermissionCommandHandler : IRequestHandler<GetMenuPermissionCommand, APIResult<List<CascadeItem>>>
    {
        private readonly IBaseRepositry<Permission> per;
        private readonly IBaseRepositry<Role> roles;
        private readonly IBaseRepositry<RolePermission> baseRepositry2;

        public GetMenuPermissionCommandHandler(IBaseRepositry<Permission> baseRepositry, IBaseRepositry<Role> baseRepositry1, IBaseRepositry<RolePermission> baseRepositry2)
        {
            per = baseRepositry;
            roles = baseRepositry1;
            this.baseRepositry2 = baseRepositry2;
        }
        public Task<APIResult<List<CascadeItem>>> Handle(GetMenuPermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CascadeItem>> result = new APIResult<List<CascadeItem>>();
            result.Code = ResultCode.Success;
            result.Message = "获取菜单权限成功";

            //如果角色id为0，则获取所有菜单权限
            if (request.RoleId == null)
            {
                var permissions = per.GetAll().ToList();
                result.Data = GetCascade(0, permissions);
                return Task.FromResult(result);
            }
            List<string> roleId = request.RoleId.Split(",").ToList();
            var list = baseRepositry2.GetAll().Where(x => roleId.Contains(x.RoleId.ToString())).ToList().Select(x => x.PermissionId);
            var permission = per.GetAll().Where(x => list.Contains(x.Id)).ToList();

            result.Data = GetCascade(0, permission);
            return Task.FromResult(result);
        }
        public List<CascadeItem> GetCascade(int parentId, List<Permission> permissions)
        {
            var result = permissions.Where(x => x.ParentId == parentId);

            List<CascadeItem> list = new List<CascadeItem>();
            foreach (var item in result)
            {
                list.Add(new CascadeItem
                {
                    Values = item.Id,
                    Label = item.PermissionName,
                    Url = item.PermissionUrl,
                    Children = GetCascade(item.Id, permissions)
                });
            }
            return list;
        }
    }
}
